//
//  WBMainViewController.swift
//  微博
//
//  Created by 康智桐 on 2018/3/27.
//  Copyright © 2018年 Kk. All rights reserved.
//

import UIKit
import SVProgressHUD

//主控制器
class WBMainViewController: UITabBarController {

    
    //定时器
     var timer:Timer?
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        //设置新特性视图方法
        setupfeatureViews()
        
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
        
        
//        //测试未读数量
//        WBNetworkManager.shared.unreadCount { (count) in
//             print("有\(count)条新微博！")
//        }
    }
    
    
    deinit {
        //销毁时钟
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
        
    }
    
    
    

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    //监听通知
    @objc func userLogin(n:Notification){
        
        print("用户登录通知\(n)")
        
        var when = DispatchTime.now()
        
        
        //判断 n的object是否有值，如果有值 提示用户重新登录
        if n.object != nil {
            //设置指示器样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户登录超时，请重新登录")
            
            //修改延时时间
            when = DispatchTime.now() + 2
            
        }
        DispatchQueue.main.asyncAfter(deadline: when ){
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            //展现登录控制器
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            
            
            self.present(nav, animated: true, completion: nil)
        }
        
        
        
        
    }
    
    
    
    //撰写微博
    @objc func composeStatue(){
        print("点击了加号按钮")
        
        
        // FIXME: 0> 判断是否登录
        
        // 1> 实例化视图
        let v = WBComposeTypeView.composeTypeView()
        
        // 2> 显示视图 - 注意闭包的循环引用
        v.show { [weak v] (clsName) in
            print(clsName)
            
            //展现撰写微博控制器
            guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
            else{
                v?.removeFromSuperview()
                return
            }
            
            
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            
            self.present(nav, animated: true) {
                v?.removeFromSuperview()
            }
            
            
        }
        
        
        
        
//        //测试设备横屏
//        let vc = UIViewController()
//        
//        vc.view.backgroundColor = UIColor.cz_random()
//        
//        let nav = UINavigationController(rootViewController: vc)
//        
//        present(nav, animated: true, completion: nil)
        
    }
    
    
    //撰写控件
    lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
  
}


extension WBMainViewController{
    
    func setupfeatureViews(){
        //检查是否登录
        if !WBNetworkManager.shared.userLogon{
            return
        }
        
        //如果更新，显示新特性。否则显示欢迎
        let  v =  isNewVersion ? WBNewFeature.newFeatureView() : WBWelcomeView.welcomeView()
        //添加视图
        //v.frame = view.bounds
        
        view.addSubview(v)
        
    }
    
    private var isNewVersion:Bool {
        
        
        //取当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        
        //保存在decument里
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print(sandboxVersion)
        //将当前版本保存在沙盒里
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //返回比较是否一致
        
        return currentVersion != sandboxVersion
    }
}



extension WBMainViewController:UITabBarControllerDelegate{
    
    //将要选择tabbar 
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("将要切换到\(viewController)")
        
        //获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        //判断当前索引是首页，同时idx也是首页 ，即重复点击按钮
        if selectedIndex == 0 && idx == selectedIndex {
            
            print("点击了首页")
            
            //让表格滚到顶部，获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            //滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0 ,y: -64), animated: true)
            
            //刷新数据 - 增加延迟，表格先滚动到顶部在刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1 , execute: {
                vc.loadData()
            })
            
            //清除未读消息
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
            
        }
        
        //判断目标控制器是否是UiViewController
        return !viewController.isMember(of: UIViewController.self)
    }
    
    
}


//时钟相关方法
extension WBMainViewController{
    
    //定义时钟
     func setupTimer(){
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        
        
        timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    
    //时钟触发方法
   @objc private  func updateTimer(){
    
        WBNetworkManager.shared.unreadCount { (count) in
            
            print("检测到\(count)条新微博")
            //设置首页 tabbarItem的badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置app的badgeNumber,从iOS8.0之后，要用户授权之后才能够显示
            UIApplication.shared.applicationIconBadgeNumber = count
            
    }
    
    }
    
}



//可以吧相近功能的函数放在一个extension中，便于维护
extension WBMainViewController{
    
     func setupComposeButton(){
        tabBar.addSubview(composeButton)
    
        //设置按钮的位置
        let count = CGFloat(childViewControllers.count)
        
        //将向内缩进宽度减少
        let w = tabBar.bounds.width / count
        //水平缩进2个button的位置
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatue), for: .touchUpInside)
        
    }
    
    //设置所有子控制器
     func setupChildControllers(){
        
        
        //从沙盒获取json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断data是否有值
        if data == nil{
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
            
        }
        
        
        
        
        //反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
            else {
            return
        }
        
//        let array:[[String:Any]] = [
//            ["clsName":"WBHomeViewController","title":"首页","imageName":"home",
//             "visitorInfo":["imageName":"","message":"关注一些人，回来看看有什么惊喜"]
//            ],
//            
//            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover",
//             "visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后，最新最热的微博尽在掌握，不会再与时事潮流擦肩而过"]
//            ],
//            
//            ["clsName":"UIViewController"],
//            
//            ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center",
//             "visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，给你发的消息，都会在这里收到通知"]
//            ],
//            
//            ["clsName":"WBProfileViewController","title":"我的","imageName":"profile",
//             "visitorInfo":["imageName":"visitordiscover_image_profile","message":"登陆后，你的微博、相册、个人资料会显示在这里，展示给别人"]
//            ],
//        ]
//        
//        
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/kkion/Desktop/demo.json", atomically: true)
        
        //遍历数组，循环创建控制器数组
    
        var arrayM = [UIViewController]()
        for dict in array!{
            arrayM.append(controller(dict: dict))
        }
        //设置tabbar的自控制器
    
        viewControllers = arrayM
        
        
    }
    
    //使用字典创建一个子控制器
    private func controller(dict:[String:Any]) -> UIViewController{
        
        //取得字典内容
        guard let clsName = dict["clsName"] as? String,
        let title = dict["title"] as? String,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String:String]
        
            else {
                return UIViewController()
        }
        //创建视图控制器
        let vc = cls.init()
        
        //设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        vc.title = title
        //设置tabbar的图片
        vc.tabBarItem.image = UIImage(named:"tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named:"tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
        
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
    
    
}
